using System;
using System.Collections.Generic;
using System.Security.Principal;
using System.Web.Mvc;
using DecisionMaking.BusinessLogic;
using DecisionMaking.Domain;
using System.Web.Security;
using MvcContrib;
using DecisionMaking.BusinessLogic.Model;

namespace DecisionMaking.WebApp.Controllers
{
	/// <summary>
	/// Responsible for all Account operations, including Login, Logout, Register and profile editing
	/// </summary>
	[HandleError]
	public class AccountController : BaseController
	{
		
		[HttpGet]
        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
				try 
				{
              		var account = AccountManager.Register(model);

                    // auto-login, no authentication
                    DoLogin(account, false);
					
					return this.RedirectToAction<HomeController>(c => c.Index());
				}
				catch (DuplicateEmailException e)
				{
					ModelState.AddModelError("Email", "This email address is already in use");
				}
            }
			
			// if we've reached here, form validation failed so we should return to the form
			return View(model);			
        }
		
		[HttpGet]
        public ActionResult Login()
        {
            return View();
        }	
		
		[HttpPost]
        public ActionResult Login(LoginModel model)
        {
        	if (ModelState.IsValid)    
			{
				try
				{
					var account = AccountManager.GetAccountByCredentials(model.Email, model.Password);
				
					DoLogin(account, model.RememberMe);
						
					return this.RedirectToAction<HomeController>(c => c.Index());
				}
				catch (AccountNotFoundException e)
				{
					ModelState.AddModelError("Email", e);
				}
			}

			return View(model);
			
        }	
		
		[HttpGet]
		public ActionResult Logout()
		{
			FormsAuthentication.SignOut();
			
			return this.RedirectToAction<HomeController>(c => c.Index());
		}

        [HttpGet]
        [Authorize]
        public ActionResult Profile()
        {
            // get a fresh copy of the account
            var account = AccountManager.GetAccount(CurrentAccount.Id);

            return
                View(new UpdateAccountModel
                         {
                             Id = account.Id,
                             Email = account.Email,
                             Bio = account.Bio,
                             FirstName = account.FirstName,
                             LastName = account.LastName
                         });
        }

        [HttpPost]
        [Authorize]
        public ActionResult Save(UpdateAccountModel model)
        {
            model.Id = CurrentAccount.Id; // prevent identity theft by restricting id to current account

            if (ModelState.IsValid)
            {
                var account = AccountManager.UpdateAccount(model);

                // put updated account into session
                this.CurrentAccount = account;

                return this.RedirectToAction(c => c.Profile());
            }

            return View("Profile", model);
        }

		
		/// <summary>
		/// Performs a login against the ASP.NET security namespace 
		/// </summary>
		private void DoLogin(Account account, bool rememberMe) 
		{
			FormsAuthentication.SetAuthCookie(account.Email, rememberMe);
			
			// save account in session
			this.CurrentAccount = account;
		}
		
	}
}

